package net.alche.sdd.fatis;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import javax.swing.Renderer;

import net.alche.al.util.AC;

import net.alche.al.util.Far;
import net.alche.al.util.M;
import net.alche.sdd.db.sqlite.DbSqliteSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings("all")
public class SddFatis {
  public String dbType = "";
  public static final Logger logger = LoggerFactory.getLogger(SddFatis.class);
  public boolean logSql = false;
  public boolean logSqlNoSelect = false;
  DataSource dataSource = null;
  SddDataSource sddSorce = null;

  public void init(Map conf) {
    // initBeeSour(conf);
    dbType = M.getStr(conf, "dbType");

    if ("sqlite".equals(dbType)) {
      initSddSour_sqlite(conf);
    } else {
      // initDruidSour(conf);
    }
    if ("true".equals(M.getStr(conf, "logSql"))) {
      logSql = true;
    }
    if ("true".equals(M.getStr(conf, "logSqlNoSelect"))) {
      logSqlNoSelect = true;
    }
  }

  public void initSddSour_sqlite(Map conf) {
    try {
      sddSorce = new DbSqliteSource(null);
      sddSorce.driver = M.getStr(conf, "driver");
      sddSorce.url = M.getStr(conf, "url");
      sddSorce.username = M.getStr(conf, "username");
      sddSorce.password = M.getStr(conf, "password");
      sddSorce.init();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  public void initSddSour(Map conf) {
    try {
      sddSorce = new SddDataSource();
      sddSorce.driver = M.getStr(conf, "driver");
      sddSorce.url = M.getStr(conf, "url");
      sddSorce.username = M.getStr(conf, "username");
      sddSorce.password = M.getStr(conf, "password");
      sddSorce.init();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  public void initBeeSour(Map conf) {
    try {
      cn.beecp.BeeDataSourceConfig config = new cn.beecp.BeeDataSourceConfig();
      config.setDriverClassName(M.getStr(conf, "driver"));
      config.setJdbcUrl(M.getStr(conf, "url"));
      config.setUsername(M.getStr(conf, "username"));
      config.setPassword(M.getStr(conf, "password"));
      // config.setMaxActive(2);
      // config.setDelayTimeForNextClear(0);
      // config.setPrintRuntimeLog(true);
      // config.setInitialSize(10);
      cn.beecp.BeeDataSource ds = new cn.beecp.BeeDataSource(config);
      dataSource = ds;
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  // public void initDruidSour(Map conf) {
  // try {
  // DruidDataSource dsour = (DruidDataSource)
  // DruidDataSourceFactory.createDataSource(conf);
  // if ("true".equals(conf.get("breakAfterAcquireFailure"))) {
  // dsour.setBreakAfterAcquireFailure(true);
  // }
  // dsour.setMaxWait(M.ior(conf, "maxWait", 800));
  // dsour.setSocketTimeout(M.ior(conf, "socketTimeout", 3000));
  // dsour.setConnectTimeout(M.ior(conf, "connectTimeout", 1200));
  // dsour.setMaxActive(M.ior(conf, "maxActive", 20));
  // dsour.setUseUnfairLock(true);
  // dsour.setPoolPreparedStatements(false);
  // dsour.setTestWhileIdle(true);
  // dataSource = dsour;
  // } catch (Exception e) {
  // e.printStackTrace();
  // }
  // }

  // public void initTomcatSour(Map conf) {
  // try {
  // org.apache.tomcat.jdbc.pool.DataSource ds = new
  // org.apache.tomcat.jdbc.pool.DataSource();
  // ds.setUrl(M.getStr(conf, "url"));
  // ds.setUsername(M.getStr(conf, "username"));
  // ds.setPassword(M.getStr(conf, "password"));
  // ds.setDriverClassName(M.getStr(conf, "driver"));
  // if (M.has(conf, "initialSize"))
  // ds.setInitialSize(Integer.parseInt(M.getStr(conf, "initialSize")));
  // if (M.has(conf, "maxIdle"))
  // ds.setMaxIdle(Integer.parseInt(M.getStr(conf, "maxIdle")));
  // if (M.has(conf, "maxActive"))
  // ds.setMaxActive(Integer.parseInt(M.getStr(conf, "maxActive")));
  // ds.setTestWhileIdle(false);
  // ds.setTestOnBorrow(false);
  // ds.setTestOnConnect(false);
  // ds.setTestOnReturn(false);
  // dataSource = ds;
  // } catch (Exception e) {
  // e.printStackTrace();
  // }
  // }

  public SddFatisStatement newConnStatement() {
    try {
      if (sddSorce != null) {
        return new SddFatisStatement(this, true, sddSorce.getConnection());
      } else {
        return new SddFatisStatement(this, getConnection());
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      return new SddFatisStatement(this, null);
    }
  }

  public SddDataSourceConnection getNewConnect() {
    try {
      if (sddSorce != null) {
        return sddSorce.getConnection();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      return null;
    }
    return null;
  }

  public SddFatisStatement getStatement() {
    return newConnStatement();
  }

  public boolean testLink() {
    String sql = "select 'X'";
    SddFatisStatement stm = newConnStatement();
    List<Map> ls = stm.select(sql);
    stm.close();
    return true;
  }

  public Connection getConnection() throws Exception {
    // long beginMs = System.currentTimeMillis();
    Connection conn = dataSource.getConnection();
    // AC.system.logRunTime(beginMs);
    return conn;
  }

  public void distory() {
    // dataSource.
  }

  /**
   * 释放资源
   */
  public static void close(Statement stmt, Connection conn) {
    close(null, stmt, conn);
  }

  /**
   * 释放资源
   */
  public static void close(ResultSet rs, Statement stmt, Connection conn) {
    if (rs != null) {
      try {
        rs.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    if (stmt != null) {
      try {
        stmt.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    if (conn != null) {
      try {
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 获取连接池
   */
  public DataSource getDataSource() {
    return dataSource;
  }
}
